package com.simple.common.exception;

import com.simple.framework.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 全局异常管理
 * @Author xiaoke
 * @Date 2024/8/10 18:00
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * DTO参数异常验证处理
     * @param e 异常类
     * @return 错误信息
     */
    @ExceptionHandler(BindException.class)
    public R<Void> methodArgumentNotValidException(BindException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> messages = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        log.error("【参数验证异常】{}",messages,e);
        return  R.fail(400,messages.get(0));
    }
    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public R<Void> doServiceException(ServiceException e) {
        log.error("【业务异常】{}",e.getMessage(),e);
        return R.fail(e.getCode(),e.getMessage());
    }
}
